Attribute VB_Name = "MarkDownManager"
Option Explicit

Sub test()
Dim i%

'ClearId
addIdAndName 100

End Sub


Sub addIdAndName(iStep As Integer, Optional startId As Integer = 1)
    Dim i%
    Dim sMD$
    Dim sName$, sUrl$
    Application.ScreenUpdating = False
    For i = 1 To iStep * 2 Step 2
        sMD = Cells(i, 1).Value
        sName = Mid(RegExpExecute(sMD, "\[(.*)\]"), 2, Len(RegExpExecute(sMD, "\[(.*)\]")) - 2)
        sUrl = Mid(RegExpExecute(sMD, "\((.*)\)"), 2, Len(RegExpExecute(sMD, "\((.*)\)")) - 2)

        AddSingleId i, i / 2 - 0.5 + startId, sName
    Next i
    Application.ScreenUpdating = True
End Sub

Sub AddSingleId(iRow As Integer, Optional id As Integer = 1, Optional sName As String = "")
    Dim i%
    
    Rows(CStr(iRow) & ":" & CStr(iRow)).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Cells(iRow, 1) = "# " & id & " " & sName
    
End Sub

Sub AddId(id As Integer, Optional startId As Integer = 1, Optional sName As String = "")
    Dim i%
    Application.ScreenUpdating = False
    Rows(1).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Cells(i * 2 + 1, 1) = "# " & startId
    For i = 1 To id - 1
        Rows(i * 2 + 1).Select
        Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        Cells(i * 2 + 1, 1) = "# " & startId + i & sName
    Next i
    Rows(1).Select
    Application.ScreenUpdating = True
End Sub


Sub ClearId(Optional lastRow As Integer = 0)
    Dim i%
    Application.ScreenUpdating = False
    If lastRow = 0 Then
        DelRow
    Else
        DelOddRow lastRow
    End If
    Application.ScreenUpdating = True
End Sub

Private Function DelOddRow(lastRow As Integer)
    Dim i%
    For i = lastRow To 1 Step -2
        Rows(i).EntireRow.Delete
    Next i
    Rows(1).Select
End Function

Private Function DelRow()
    Dim i%
    Dim lastRow%
    lastRow = Cells(65536, 1).End(xlUp).Row + (Cells(65536, 1).End(xlUp).Row Mod 2) - 1
    For i = lastRow To 1 Step -2
        Rows(i).EntireRow.Delete
    Next i
    Rows(1).Select
End Function


'依赖函数-正则表达式

Public Function RegExpExecute(iput As Variant, sRule As String)
    '字符串提取
    Dim mj As String, m As Object
    Dim i%
    Dim reg As Object
    Set reg = CreateObject("vbscript.regexp")
    With reg
        .Pattern = sRule '规则
        .Global = True '多次匹配还是一次
        .IgnoreCase = True '是否区分大小写
        .MultiLine = True  '搜索字符串是否分布在多行
    End With
    
    '输出=reg.Execute(输入)
    '正则拆出来的东西是集合，而不是字符串，所以不能Value或Range输出
    Set m = reg.Execute(iput)
    
    
    For i = 0 To m.Count - 1
        mj = mj & m.Item(i).Value
    Next i
    
    RegExpExecute = mj
End Function